package com.atguigu.datastream.test.day03;

import com.atguigu.datastream.bean.Event;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.ParallelSourceFunction;

import java.util.Random;

/**
 * ClassName: Flink_05_Source_useDefault
 * Package: com.atguigu.test.day03
 * Description:
 *
 * @Author ChenJun
 * @Create 2023/4/9 19:50
 * @Version 1.0
 */
public class Flink_05_Source_useDefault {
    public static void main(String[] args) throws Exception {

        //1. 创建 flink 流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //2. 设置并行度
        env.setParallelism(1);

        //3. 创建数据流
        DataStreamSource<Event> streamSource = env.addSource(new ClickSource()).setParallelism(2);

        //4. 打印
        streamSource.print();

        //5. 执行
        env.execute();
    }
//    public static class ClickSource implements SourceFunction<Event> {

    // 设置并行度的接口
    public static class ClickSource implements ParallelSourceFunction<Event> {
        private Boolean isRunning = true;

        @Override
        public void run(SourceContext<Event> sourceContext) throws Exception {
            System.out.println("----------数据生成-----------");
            Random random = new Random();

            String[] users = {"Songsong", "Bingbing"};
            String[] urls = {"./home", "./cart", "./fav", "./prod?id=1", "./prod?id=2"};

            while (true){
                sourceContext.collect(new Event(users[random.nextInt(users.length)],urls[random.nextInt(urls.length)]
                        ,System.currentTimeMillis()));
                Thread.sleep(200);
            }
        }

        @Override
        public void cancel() {
            System.out.println("------------数据关闭---------------");
            isRunning = false;
        }
    }
}
